<template>
  <view class="content_page" :style="{ paddingTop: `${statusBarHeight}px` }">
    <view class="title" style="padding-left: 32rpx; margin-top: 10rpx">设备</view>
    <view class="weather_box" :style="{ paddingBottom: globalFont == 'small_font' ? '0' : '10px' }">
      <div v-if="weatherRes">
        <div class="weather_box_top">
          <image :src="weatherList[weatherRes.icon]"></image>
          <div class="title">{{ weatherRes.temp }}℃</div>
        </div>
        <div class="weather_box_main">
          <div class="flex">
            <div :class="['top', globalFont]">{{ weatherRes.windDir
            }}({{ weatherRes.windLevel }}级)</div>
            <div :style="{ fontSize: globalFont == 'small_font' ? '24rpx' : '36rpx' }" class="btm">风速</div>
          </div>
          <div class="flex">
            <div :class="['top', globalFont]">{{ weatherRes.humidity }} %</div>
            <div :class="['btm', globalFont]">室外湿度</div>
          </div>
        </div>
      </div>
      <div v-if="!weatherScope" class="scope_box">
        <div :style="{
          fontSize: globalFont == 'small_font' ? '28rpx' : (globalFont == 'small_font' ? '34rpx' : '40rpx'),
          lineHeight: globalFont == 'small_font' ? '30px' : '34px'
        }" class="title">
          未获得位置授权无法获取天气，请前往授权
        </div>
        <div @click="toSettingScope" :class="['btn', globalFont]">去授权</div>
      </div>
    </view>
    <!-- 设备分类 -->
    <view class="device_sort">
      <div class="group_tab">
        <up-tabs :list="arrList" :current="currenttabIndex" lineWidth="30" lineColor="#006D56" :activeStyle="{
          color: '#006D56',
          fontWeight: 'bold',
          transform: 'scale(1.05)',
          fontSize: globalFont === 'small_font' ? '28rpx' : globalFont === 'small-medium' ? '32rpx' : '40rpx',
        }" :inactiveStyle="{
          color: '#606266',
          transform: 'scale(1)',
          fontSize: globalFont === 'small_font' ? '28rpx' : globalFont === 'small-medium' ? '32rpx' : '40rpx',
        }" itemStyle="padding-left: 15px; padding-right: 15px; height: 50px;" @click="chooseGroup">
        </up-tabs>
      </div>
      <div class="fixed_right" @click="addGroup">
        <image src="/static/home/plus-circle@2x.png" alt="add icon" class="add_icon" />
      </div>
    </view>
    <scroll-view scroll-y="true" class="scroll-Y">
      <!-- 循环设备 -->
      <view class="device_item" v-for="(i, k) in dataList">
        <view class="first_box">
          <view class="flex_around" :class="['device_name', globalFont]">
            <view style="display: flex; width: 600rpx;flex-wrap: wrap;">
              <view style="margin-right: 40rpx;">{{ i.equipmentName }}</view>
              <view>{{ i.categoryName }}</view>
            </view>
            <view style="width: 80rpx; height:80rpx;display: flex;justify-content: center;align-items: center" @click="toSettingPage(i)"> 
              <image src="/static/home/icon_set up@2x.png" alt="" 
                style="width: 54rpx; height: 54rpx"></image>
            </view>
          </view>
        </view>
        <view class="second_box ">
          <view class=""></view>
          <view class="flex_center" v-if="i.workStatus !== 0 && i.networkStatus">
            <view class="icon"></view>
            <view class="device_working_status outline"
              :style="{ fontSize: globalFont == 'small_font' ? '22rpx' : globalFont == 'small-medium' ? '30rpx' : '36rpx' }">
              {{
                workTypeMap[i.workStatus] }}中</view>
          </view>
          <view class="flex_center" v-if="!i.networkStatus">
            <view class="icon"></view>
            <view class="device_working_status outline"
              :style="{ fontSize: globalFont == 'small_font' ? '22rpx' : globalFont == 'small-medium' ? '30rpx' : '36rpx' }">
              离线</view>
          </view>
          <view>
          </view>
          <view class="device_address"
            :style="{ fontSize: globalFont == 'small_font' ? '22rpx' : globalFont == 'small-medium' ? '30rpx' : '36rpx' }">
            {{
              i.installLocation
            }}</view>
          <view class="device_number flex_center">
            <view class="outline device_working_status" style="border: none"
              :style="{ fontSize: globalFont == 'small_font' ? '22rpx' : globalFont == 'small-medium' ? '30rpx' : '36rpx' }">
              设备编号:{{
                i.equipmentNo }}</view>
          </view>
        </view>
        <!-- 告警信息 -->
        <view class="warning flex_between" v-if="i.warnStatus && i.networkStatus" @click="toWarning(i)">
          <up-notice-bar :text="i.warnMsg" bgColor="#F8EDED" color="#C92A2A" speed="50"
            :fontSize="globalFont == 'small_font' ? 13 : 18" v-if="i.warnMsg.length > 26"></up-notice-bar>
          <view v-else :class="['warning_title', globalFont]">
            <up-icon name="volume" size="19" color="#C92A2A"></up-icon>
            <view style="margin-left: 10rpx;"> {{ i.warnMsg }}</view>
          </view>
        </view>
        <view class="third flex_between">
          <!-- 循环下面这个盒子 -->
          <view class="device_working flex_center_center" v-for="(f, m) in i.resultList" :key="m" :style="{
            width: f.type === 2 && i.resultList.length == 3 && globalFont == 'small_font' ? '60%' : bucketWidth1[i.resultList.length]
          }" :class="[
            'device_working_status',
            globalFont,
            {
              isactive: i.isSelected == f.type,
              gray: i.lockStatus || (f.bucket1DrugRemainRatio == 0 && f.type == 2) || !i.networkStatus,
              'column-layout': i.resultList.length == 3 && globalFont !== 'small_font'
            }
          ]" @click="choosetype(i, f)">
            <div class="activeimg" v-if="i.isSelected == f.type">
              <image src="/static/home/icon_Selected.png"></image>
            </div>
            <image src="/static/Index/home_icon_ws@2x.png" v-if="f.type == 1" class="wx_img"></image>
            <image src="/static/Index/home_icon_qw@2x.png" v-if="f.type == 2" class="qw_img"></image>
            <image src="/static/Index/home_icon_jw@2x.png" v-if="f.type == 6" class="jw_img"></image>
            <div class="info_box">
              <div :class="['info_box_title', globalFont]" :style="{
                textAlign: i.resultList.length === 3 && globalFont !== 'small_font' ? 'center' : 'left',
              }">
                {{ workTypeMap[f.type] }}
              </div>
              <div
                :style="{ 'font-size': globalFont === 'small_font' ? '20rpx' : globalFont === 'small-medium' ? '24rpx' : '26rpx' }"
                class="info_box_radio" v-if="f.type == 2">
                余量：{{ f.bucket1DrugRemainRatio || 0 }}%
              </div>
            </div>
          </view>
        </view>
        <!-- 操作按钮 -->
        <view class="device_btn" v-if="i.networkStatus" :class="[
          'device_working_status',
          globalFont,
          {
            device_start_btn: i.workStatus == 0,
            device_working_btn: i.workStatus == 2 || !selectedStates[i.equipmentId] && i.drugRemainRatio == 0 && i.workType.split(',').includes('2'),
            device_stop_btn: ![0, 2].includes(i.workStatus),
          }
        ]" @click="toWork(i)">
          {{ workStatusMap[i.workStatus] }}
        </view>
      </view>
      <!-- 循环完毕添加设备-->
      <view v-if="dataList.length" @click="toaddDevcie">
        <view class="flex_center_center" :class="['device_add', globalFont]">
          <image src="/static/home/icon_tianjia.png" alt="" style="margin-right: 20rpx" />
          <view>添加设备</view>
        </view>
        <view class="space"></view>
      </view>
      <!-- 没有设备添加设备 -->
      <view class="blank" v-else @click="toaddDevcie" :class="['blank', globalFont]">
        <image src="/static/home/img_zanwu.png"></image>
        <text>暂无设备</text>
        <view class="bkank_add flex_center_center" :class="['bkank_add', globalFont]">
          <image src="/static/home/tianjia.png"></image>
          <text>添加设备</text>
        </view>
      </view>
    </scroll-view>
    <!-- 开始工作的时间选择 -->
    <div class="index_madal">
      <up-popup :show="device_work.showModal" z-index="999999999" mode="bottom" :round="16">
        <view class="title addtitle">
          <div style="width: 40rpx"></div>
          <text>{{ device_work.showDurtionTitle }}</text>
          <image src="/static/home/close.png" @click="device_work.showModal = false"></image>
        </view>
        <view class="part borderLine mt114" v-if="submitForm.sprayModel != 2">
          <up-picker :show="device_work.showModal" ref="uPickerRefTwo" :columns="columns" keyName="value"
            :defaultIndex="defaultIndex"></up-picker>
          <view class="modalBtn">
            <view class="btn" @click="confirmSubmit">确认</view>
          </view>
        </view>
        <view v-else class="Mosquito_time">
          <div class="choose_modal flex_between">
            <div :class="['choose_modal_time', globalFont, { activeTime: activeTime == i.title }]"
              v-for="(i, k) in MosquitoTime" :key="k" @click="chooseTime(i)">
              {{ i.title }}分钟
              <div class="activeimg" v-if="activeTime == i.title">
                <image src="/static/home/icon_Selected.png"></image>
              </div>
            </div>
          </div>
          <view :class="['modalBtn_two', globalFont]">
            <view class="btn" @click="confirmSubmit">确认</view>
          </view>
        </view>
      </up-popup>
    </div>
    <!-- 删除弹框 -->
    <div class="delModal">
      <up-modal :show="stopworkModal.showModal" title="提示" :content="stopworkModal.stopContent" @confirm="confirmStop"
        @cancel="stopworkModal.showModal = false" :showCancelButton="true"></up-modal>
    </div>
    <!-- 添加分类 -->
    <div class="editModal">
      <up-modal :show="editDevice.showModal" title="添加分组" showCancelButton="true" @confirm="confirmChange"
        @cancel="editDevice.showModal = false">
        <view class="slot-content">
          <up-input placeholder="请输入分组名称" border="bottom" v-model="editDevice.groupName" input-align="left"
            style="width: 100%"></up-input>
        </view>
      </up-modal>
    </div>
    <!-- 设备被锁定-->
    <div class="editModal">
      <up-modal :show="bindDevice.visiable" title="提示" content="该设备已被锁定，请联系管理员"
        @confirm="bindDevice.visiable = false"></up-modal>
    </div>
    <div class="editModal">
      <!-- 设备分享已过期 -->
      <up-modal :show="shraeModal" title="提示" content="链接超过24小时已失效!" @confirm="logout"></up-modal>
    </div>
  </view>
</template>
<script setup lang="ts">
import { weatherList } from "@/utils/configData.ts";
import { ref, getCurrentInstance, computed } from "vue";
import { columns } from "@/utils/configData.ts";
import { onShow, onHide, onLoad } from "@dcloudio/uni-app";
import { loginFn } from "../../api/login/login.ts";
import {
  deviceSortFn,
  addeditGroupFn,
  devlceListFn,
  deviceWorkFn,
  getWeatherInfo,
  share
} from "../../api/index/index.ts";
import type { DeviceSortType, deviceListType } from "@/api/index/type.ts";
import { options } from "axios";
const statusBarHeight = ref<string>("");
const currenttabIndex = ref(0);
// -----一些枚举数值
const MosquitoTime = ref<{ id: number; title: string }[]>([
  {
    id: 1,
    title: "1",
  },
  {
    id: 2,
    title: "2",
  },
  {
    id: 3,
    title: "3",
  },
]);
const bucketWidth1: Record<number, string> = {
  3: "40%",
  2: "50%",
  1: "100%",
};
const workTypeMap: Record<string, string> = {
  "1": "雾森",
  "2": "驱蚊",
  "6": "降温",
};
const workStatusMap: Record<string, string> = {
  "0": "开始",
  "1": "停止",
  "2": "驱蚊中",
  "6": "停止",
};
// 设别锁定
const bindDevice = ref({
  visiable: false,
});
// 设备分类
const deviceSort = ref<DeviceSortType[]>([]);
const arrList = ref<{ id: string; name: string }[]>([]);
const groupId = ref();
const getsortList = () => {
  deviceSortFn()
    .then((res: any) => {
      if (res.resultStatus) {
        deviceSort.value = res.resultData;
        arrList.value = deviceSort.value.map((f: any) => {
          return {
            id: f.groupId,
            name: f.groupName,
          };
        });
        arrList.value.unshift({
          id: "",
          name: "全部",
        });
        groupId.value = arrList.value[0].id;
        currenttabIndex.value = 0;
        getDataList();
      } else {

      }
    })
    .catch((err: any) => {
      uni.showToast({
        title: "服务器异常",
        icon: "none",
      });
    });
};
const dataList = ref<deviceListType[]>([]);
const isLoading = ref(true);
const selectedStates = ref<any>({})
const getDataList = () => {
  // dataList.value = [
  //   {
  //     equipmentId: 1,
  //     equipmentNo: "202410232024102320241023",
  //     equipmentName: "设备名称1设备名称1设备名称1设备名称1设备名称1",
  //     categoryName: "NSW-001",
  //     workType: "1,2,6",
  //     installLocation: "公寓",
  //     workStatus: 1,
  //     networkStatus: true,
  //     warnStatus: true,
  //     warnMsg: "设备已运行50小时，请更换泵头润滑油并检查过滤瓶滤芯！",
  //     lastReportTime: "2025-1-20 14:37:00",
  //     drugRemainRatio: 0,
  //     lockStatus: false,
  //     cleanTime: "20",
  //     waterPressure: "50",
  //     coolStatus: false,
  //     lat: 39.91488908,
  //     lng: 116.40387397,
  //     temperatureStatus: true,
  //   },
  //   {
  //     equipmentId: 1,
  //     equipmentNo: "20241023",
  //     equipmentName: "设备名称1",
  //     categoryName: "NSW-002",
  //     workType: "1,2,6",
  //     installLocation: "公寓",
  //     workStatus: 2,
  //     networkStatus: true,
  //     warnStatus: true,
  //     warnMsg: "设备已运行50小时，请更换泵头润滑油并检查过滤瓶滤芯！",
  //     lastReportTime: "2025-1-20 14:37:00",
  //     drugRemainRatio: 11,
  //     lockStatus: false,
  //     cleanTime: "20",
  //     waterPressure: "50",
  //     coolStatus: false,
  //     lat: 39.91488908,
  //     lng: 116.40387397,
  //     temperatureStatus: true
  //   },
  // ];
  // dataList.value = dataList.value.map((f: any) => {
  //   let workTypeArray = f.workType.split(",").map(Number);
  //   if (f.categoryName !== 'NSW-002' && !f.temperatureStatus) {
  //     workTypeArray = workTypeArray.filter(type => type !== 6);
  //   }
  //   const customOrder = [2, 1, 6];
  //   const workType = workTypeArray.sort((a, b) => {
  //     return customOrder.indexOf(a) - customOrder.indexOf(b);
  //   });
  //   f.workType = workTypeArray.join(',')
  //   const resultList = workType.map((i: any) => {
  //     return {
  //       type: Number(i),
  //       bucket1DrugRemainRatio: i == 2 ? f.drugRemainRatio || '0' : 0,
  //     };
  //   });
  //   let isSelected;
  //   if (f.workStatus !== 0) {
  //       isSelected = f.workStatus;
  //   }
  //   if (f.networkStatus === false) {
  //     isSelected = undefined;
  //   } else if (selectedStates.value[f.equipmentId] !== undefined && f.workStatus == 0 ) {
  //     isSelected = selectedStates.value[f.equipmentId];
  //   } else if (f.lockStatus) {
  //     isSelected = false;
  //   } else if (f.workStatus == 0) {
  //     if (f.categoryName == 'NXW-001') {
  //       isSelected = '2'
  //     } else if (f.categoryName == 'NXW-002') {
  //       isSelected = '1'
  //     } else {
  //       isSelected = resultList[0]?.type
  //     }
  //   } else {
  //     isSelected = f.workStatus;
  //   }
  //   selectedStates.value[f.equipmentId] = isSelected;
  //   return {
  //     ...f,
  //     isSelected: isSelected,
  //     resultList,
  //   };
  // });
  // return
  devlceListFn({ groupId: groupId.value })
    .then((res: any) => {
      if (res.resultStatus) {
        dataList.value = res.resultData;
        dataList.value = dataList.value.map((f: any) => {
          let workTypeArray = f.workType.split(",").map(Number);
          if (f.categoryName !== 'NSW-002' && !f.temperatureStatus) {
            workTypeArray = workTypeArray.filter(type => type !== 6);
          }
          const customOrder = [2, 1, 6];
          const workType = workTypeArray.sort((a, b) => {
            return customOrder.indexOf(a) - customOrder.indexOf(b);
          });
          f.workType = workTypeArray.join(',')
          const resultList = workType.map((i: any) => {
            return {
              type: Number(i),
              bucket1DrugRemainRatio: i == 2 ? f.drugRemainRatio || '0' : 0,
            };
          });
          let isSelected;
          if (f.workStatus !== 0) {
            isSelected = f.workStatus;
            selectedStates.value[f.equipmentId] = isSelected;
          }
          if (f.networkStatus === false) {
            isSelected = undefined;
          } else if (selectedStates.value[f.equipmentId] !== undefined && f.workStatus == 0) {
            isSelected = selectedStates.value[f.equipmentId];
          } else if (f.lockStatus) {
            isSelected = false;
          } else if (f.workStatus == 0) {
            if (f.categoryName == 'NXW-001') {
              isSelected = '2'
            } else if (f.categoryName == 'NXW-002') {
              isSelected = '1'
            } else {
              isSelected = resultList[0]?.type
            }
          }
          return {
            ...f,
            isSelected: isSelected,
            resultList,
          };
        });
      }
    })
    .catch((err: any) => {
      uni.showToast({
        title: "服务器异常",
        icon: "none",
      });
    })
    .finally(() => {
      // uni.hideLoading();
    });
};
const chooseGroup = (e: any) => {
  groupId.value = e.id;
  currenttabIndex.value = e.index;
  getDataList();
};
// 点击工作类型
const choosetype = (i: any, f: any) => {
  if ((f.bucket1DrugRemainRatio == 0 && f.type == 2) || i.lockStatus) {
    return;
  }
  if (!i.networkStatus) {
    return
  }
  if (i.workStatus) {
    return
  }
  if (i.lockStatus) {
    bindDevice.value.visiable = true;
    return;
  }
  i.isSelected = f.type
  selectedStates.value[i.equipmentId] = i.isSelected;
};
// 工作---------
const device_work = ref<{
  workType: string;
  showDurtionTitle: string;
  showModal: boolean;
  uPickerRefTwo: any;
  workTime: string;
}>({
  workType: "",
  showDurtionTitle: "",
  showModal: false,
  uPickerRefTwo: null,
  workTime: "",
});
const uPickerRefTwo = ref<any>(null);
const stopworkModal = ref<{
  showModal: boolean;
  stopContent: string;
}>({
  showModal: false,
  stopContent: "",
});
const submitForm = ref({
  equipmentId: 0,
  sprayModel: 0,
  dataTime: "",
});
// 选择驱蚊时长
const activeTime = ref("1");
const Mosquito = ref("1:0");
const chooseTime = (i: { id: number; title: string }) => {
  activeTime.value = i.title;
  Mosquito.value = `${i.title}:0`;
};
const toWork = (i: any) => {
  if (!selectedStates.value[i.equipmentId] && i.drugRemainRatio == 0 && i.workType.split(',').includes('2')) {
    uni.showToast({
      title: "驱蚊药液不足，请及时补充",
      icon: "none",
    });
    return
  }
  if (i.workStatus == 2) {
    return;
  }
  if (i.lockStatus) {
    bindDevice.value.visiable = true;
    return;
  }
  submitForm.value.equipmentId = i.equipmentId;
  submitForm.value.sprayModel = i.workStatus == 0 ? i.isSelected : 0;
  device_work.value.workType = i.workStatus;
  if (i.workStatus == 0) {
    device_work.value.showDurtionTitle =
      i.isSelected == 1
        ? "请选择雾森时长"
        : i.isSelected == 2
          ? "请选择驱蚊时长"
          : "请选择降温时长";
    const defaultTime = "01:00";
    device_work.value.showModal = true;
    defaultIndex.value = defaultTime
      .split(":")
      .map((f: string) => parseInt(f, 10));
  } else {
    stopworkModal.value.showModal = true;
    stopworkModal.value.stopContent = `您确定要停止${workTypeMap[i.isSelected]
      }吗`;
  }
};
const stopBtn = ref(false)
const confirmStop = () => {
  if (stopBtn.value) {
    return
  }
  stopBtn.value = true
  uni.showLoading({
    title: "停止中...",
  });
  deviceWorkFn({
    equipmentId: submitForm.value.equipmentId,
    sprayModel: submitForm.value.sprayModel,
  })
    .then((res: any) => {
      if (res.resultStatus) {
        uni.showToast({
          title: "操作成功",
          icon: "none",
        });
        getDataList();
      } else {
        uni.showToast({
          title: res.errorMessage,
          icon: "none",
        });
      }
    })
    .catch((err: any) => {
      uni.showToast({
        title: "服务器异常",
        icon: "none",
      });
    })
    .finally(() => {
      setTimeout(() => {
        uni.hideLoading()
        stopBtn.value = false
      }, 2000)
      stopworkModal.value.showModal = false;
    });
};
// 确定开始工作
const defaultIndex = ref();
const confirmSubmit = () => {
  const arr =
    submitForm.value.sprayModel == 2
      ? Mosquito.value.split(":")
      : uPickerRefTwo.value.innerIndex;
  const seconds = arr[0] * 60 + arr[1];
  console.log(seconds, 'arrrr');
  if (seconds < 20) {
    uni.showToast({
      title: `工作时长不能小于20秒`,
      icon: "none",
    });
    return
  }
  if (submitForm.value.sprayModel !== 2) {
    if (arr[0] < 1) {
      uni.showToast({
        title: "工作时长必须大于一分钟，请重新选择",
        icon: 'none'
      })
      return
    }
  }
  uni.showLoading({
    title: "操作中...",
  });

  deviceWorkFn({
    equipmentId: submitForm.value.equipmentId,
    sprayModel: submitForm.value.sprayModel,
    workMinute: submitForm.value.sprayModel == 2 ? Number(arr[0]) : arr[0],
    workSecond: submitForm.value.sprayModel == 2 ? Number(arr[1]) : arr[1],
  })
    .then((res: any) => {
      if (res.resultStatus) {
        uni.showToast({
          title: "操作成功",
          icon: "none",
        });
        getDataList();
      } else {
        uni.showToast({
          title: res.errorMessage,
          icon: "none",
        });
      }
    })
    .catch((err: any) => {
      uni.showToast({
        title: "服务器异常",
        icon: "none",
      });
    })
    .finally(() => {
      stopworkModal.value.showModal = false;
    });
  device_work.value.showModal = false;
};
// 跳转添加设备页面
const toaddDevcie = () => {
  uni.scanCode({
    scanType: ["qrCode"],
    onlyFromCamera: true,
    success: (res) => {
      const equipmentId = res.result.split("?")[1].split("=")[1]; // 从扫码结果中提取设备ID
      uni.navigateTo({
        url: `/pages/addDevice/addDevice?equipmentId=${equipmentId}`,
      });
    },
    fail: (err) => {
      console.error("扫码失败", err);
    },
  });
};
// 跳转详情页
const instance = getCurrentInstance();
const appStorage = instance?.appContext.config.globalProperties.appStorage;
const toSettingPage = (i: any) => {
  if (i.lockStatus) {
    bindDevice.value.visiable = true;
    return;
  }
  appStorage.setObj("device_info", i);
  uni.navigateTo({
    url: `/pages/setDevice/settingPage`,
  });
};
// 去到告警页面
const toWarning = (i: any) => {
  if (i.lockStatus) {
    bindDevice.value.visiable = true;
    return;
  }
  uni.navigateTo({
    url: `/pages/toTab/warningInfo?equipmentId=${i.equipmentId}`,
  });
};
// 添加设备分组
const editDevice = ref(<
  { showModal: boolean; groupName: string; groupId: number }
  >{
    showModal: false,
    groupName: "",
    groupId: 0,
  });
const addGroup = () => {
  editDevice.value.showModal = true;
};
const confirmChange = () => {
  addeditGroupFn(editDevice.value.groupId, {
    groupName: editDevice.value.groupName,
  })
    .then((res: any) => {
      if (res.resultStatus) {
        uni.showToast({
          title: "添加成功",
          icon: "none",
        });
        getsortList();
      } else {
        uni.showToast({
          title: res.errorMessage,
        });
      }
    })
    .catch((err: any) => {
      uni.showToast({
        title: "服务器异常",
        icon: "none",
      });
    })
    .finally(() => {
      editDevice.value.showModal = false;
    });
};
// 获取实时天气
const weatherRes = ref();
const weatherScope = ref(false)
const checkLogin = (str: any) => {
  getWeatherInfo({
    lat: str.latitude,
    lng: str.longitude,
  })
    .then((res: any) => {
      if (res.resultStatus) {
        weatherScope.value = true
        weatherRes.value = res.resultData;
      } else {

      }
    })
    .catch((err: any) => {
      console.log(err);
    });
};
const getLocationInfo = () => {
  uni.getLocation({
    type: "wgs84",
    success: function (res) {
      appStorage.setObj("weatherInfo", res);
      weatherScope.value = true
      checkLogin(res);
    },
    fail: (err) => {
      console.log(err, 'errerr')
      weatherScope.value = false
      uni.showToast({
        title: '获取位置失败',
        icon: 'none',
      });
    }
  });
}
// 请求位置授权
const requestLocationPermission = () => {
  uni.authorize({
    scope: "scope.userLocation",  // 请求位置授权
    success: function () {

      getLocationInfo();  // 授权成功，获取位置
    },
    fail: function () {
      // uni.showToast({
      //   title: '授权失败，请在设置中开启定位权限',
      //   icon: 'none',
      // });
    }
  });
};
const checkLocationPermission = () => {
  uni.getSetting({
    success(res) {
      const authSetting = res.authSetting;
      console.log(authSetting, 'autosetting');
      // 如果用户没有设置过权限，或者首次打开应用，需要授权
      if (!authSetting["scope.userLocation"] || authSetting["scope.userLocation"] === false) {
        requestLocationPermission();
      } else if (authSetting["scope.userLocation"] === true) {
        getLocationInfo();  // 用户已授权，直接获取位置
      }
    }
  });
};
const toSettingScope = () => {
  uni.getSetting({
    success: (res) => {
      if (!res.authSetting['scope.userLocation']) {
        // 未授权，则发起授权请求
        uni.authorize({
          scope: 'scope.userLocation',
          success: () => {
            getLocationInfo();
          },
          fail: () => {
            uni.showModal({
              title: '提示',
              content: '需要您授权位置信息才能获取天气，是否去设置页面开启授权？',
              confirmText: '去设置',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  uni.openSetting({
                    success: (settingRes) => {
                      if (settingRes.authSetting['scope.userLocation']) {
                        console.log(settingRes);
                      }
                    }
                  });
                }
              }
            });
          }
        });
      } else {
        getLocationInfo();
      }
    }
  });
}
// 静默登录逻辑
const wxSilentLogin = () => {
  return new Promise((resolve, reject) => {
    uni.login({
      success(res) {
        console.log(res, "p1");
        resolve(res.code);
      },
      fail(err) {
        console.log(err, "错误1");
        reject(err);
      },
    });
  });
};
const WXLogin = (data: any) => {
  loginFn(data)
    .then((res: any) => {
      if (res.resultStatus) {
        if (appStorage) {
          res.resultData["smallFont"] = "small-medium";
          appStorage.setObj("userInfo_key", res.resultData);
          getsortList()
          const shareEquipmengId = appStorage.getObj("shareInfo");
          if (Object.keys(shareEquipmengId).length !== 0) {
            shareMessage(shareEquipmengId)
          }
        }
      }
    })
    .catch((err: any) => {
      console.log(err);
    });
};
const toLogin = () => {
  let p1 = wxSilentLogin();
  Promise.all([p1])
    .then((res) => {
      let code = res[0];
      const data = {
        code: code,
      };
      WXLogin(data);
    })
    .catch((err) => {
      console.log(err);
    });
}
const intervalId = ref();
const globalFont = ref();
onShow(() => {
  const getNavHeight =
    getCurrentInstance()?.appContext.config.globalProperties.getnavHeight();
  statusBarHeight.value = getNavHeight;
  // 静默登录判断
  const weatherInfo = appStorage.getObj("weatherInfo");
  if (Object.keys(weatherInfo).length === 0) {
    checkLocationPermission()
  } else {
    checkLogin(weatherInfo)
  }
  const userInfo = appStorage.getObj("userInfo_key");
  globalFont.value = userInfo.smallFont
  if (Object.keys(userInfo).length === 0) {
    toLogin()
  } else {
    getsortList()
    intervalId.value = setInterval(() => {
      getDataList();
    }, 5000);
  }
});
const shareMessage = (id: any) => {
  share({ equipmentId: id }).then((res: any) => {
    if (res.resultStatus) {
      getsortList();
    } else {
      toLogin()
    }
  }).catch((err) => {
    console.log(err);
  })
}
// 分享设备过期
const shraeModal = ref(false);
const logout = () => {
  uni.exitMiniProgram({
    success: function () {
      console.log('成功');
    },
    fail: function () {
      console.log('失败');
    }
  });
}
onLoad((options) => {
  // shareMessage('202504030003')
  if (options?.equipmentId) {
    appStorage.setObj("shareInfo", options.equipmentId);
    const data = options.timestamp
    const timestamp = new Date(data).getTime();
    const currentTime = new Date().getTime();
    const twentyFourHoursLater = timestamp + (24 * 60 * 60 * 1000);
    if (currentTime > twentyFourHoursLater) {
      shraeModal.value = true
    } else {
      const userInfo = appStorage.getObj("userInfo_key");
      if (Object.keys(userInfo).length === 0) {
        toLogin()
      } else {
        shareMessage(options.equipmentId)
      }
    }
  }
})
onHide(() => {
  clearInterval(intervalId.value);
});
</script>

<style lang="scss" scoped>
:root {
  /* 默认字号 */
  --font-size-small: 26rpx;
  /* 中号字号 */
  --font-size-medium: 32rpx;
  /* 大号字号 */
  --font-size-large: 40rpx;
}

.small_font {
  font-size: var(--font-size-small);
}

.small-medium {
  font-size: var(--font-size-medium);
}

.small-large {
  font-size: var(--font-size-large);
}

.content_page {
  height: calc(100vh - 94rpx);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background: #f5f6f7;

  .scroll-Y {
    flex: 1;
    overflow-y: auto;
  }

  .title {
    // font-size: 36rpx;
    font-weight: bold;
    padding-bottom: 0;
  }

  .weather_box {
    background: url("/static/Index/bj2.png");
    background-size: cover;
    width: 100%;
    height: 300rpx;
    margin: 38rpx auto 0;
    font-weight: bold;
    text-align: left;
    display: flex;
    flex-direction: column;


    .scope_box {
      padding: 52rpx 0 0 40rpx;
      width: 414rpx;

      .title {
        // font-size: 24rpx;
        color: #7d8c91;
        // line-height: 30px;
        text-align: left;
      }

      .btn {
        width: 172rpx;
        height: 64rpx;
        opacity: 0.46;
        background: #000000;
        border-radius: 32rpx;
        opacity: 0.46;
        background: #000000;
        margin-top: 48rpx;
        color: #ffffff;
        text-align: center;
        line-height: 64rpx;
      }

      // .small_font {
      //   font-size: var(--font-size-small);
      // }

      // .small-medium {
      //   font-size: var(--font-size-medium);
      // }

      // .small-large {
      //   font-size: var(--font-size-large);
      // }
    }

    /* 让天气顶部和底部垂直布局 */
    .weather_box_top {
      margin-top: 22px;
      width: 100%;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      height: 50%;

      /* 限制顶部盒子的高度，防止它撑大父盒子 */
      image {
        width: 52px;
        height: 52px;
        margin-left: 40px;
      }

      .title {
        color: #333;
        font-size: 38px;
        font-weight: bold;
        margin-left: 34px;
      }
    }

    .weather_box_main {
      width: 100%;
      display: flex;
      justify-content: space-around;
      align-items: center;
      height: 50%;

      .flex {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: flex-start;
        text-align: left;

        .top {
          // font-size: 24rpx;;
          font-weight: bold;
          color: #7d8c91;
          margin-bottom: 6rpx;
        }

        .btm {
          // font-size: 24rpx;;
          color: #7d8c91;
          font-weight: normal;
        }

        // .small_font {
        //   font-size: var(--font-size-small);
        // }

        // .small-medium {
        //   font-size: var(--font-size-medium);
        // }

        // .small-large {
        //   font-size: var(--font-size-large);
        // }
      }
    }
  }

  .device_sort {
    height: 140rpx;
    margin-top: 36rpx;
    position: relative;
    background: linear-gradient(180deg, #ffffff 36%, #f8f8f8);
    border-radius: 20px 0px 0px 20px;
    padding: 40rpx 0 0 40rpx;
    display: flex;
    position: relative;

    .group_tab {
      width: calc(100% - 120rpx);
      overflow: scroll;
    }

    .fixed_right {
      position: absolute;
      top: 22rpx;
      right: 0;
      width: 120rpx;
      height: 120rpx;
      display: flex;
      justify-content: center;
      align-items: center;

      .add_icon {
        width: 52rpx;
        height: 52rpx;
      }
    }
  }

  .device_item {
    width: 686rpx;
    margin: 28rpx auto;
    height: auto;
    padding: 42rpx 0;
    box-sizing: border-box;
    background: #ffffff;
    border-radius: 16rpx;
    box-shadow: 0 0 40rpx 0 rgba(0, 0, 0, 0.09);

    .first_box {
      margin: 0 40rpx;

      .device_name {
        // font-size: 24rpx;;
        color: #000000;
        font-weight: bold;

        image {
          width: 32rpx;
          height: 32rpx;
        }
      }

      // .small_font {
      //   font-size: var(--font-size-small);
      // }

      // .small-medium {
      //   font-size: var(--font-size-medium);
      // }

      // .small-large {
      //   font-size: var(--font-size-large);
      // }
    }

    .second_box {
      margin: 10rpx 40rpx 32rpx;
      display: flex;
      // justify-content: space-between;
      flex-wrap: wrap;
      align-items: center;

      .device_address {
        // font-size: 24rpx;

        color: #999;
        padding: 0 14rpx;
        border-right: 2rpx solid #e9e9e9;
      }

      .device_working_status {
        // font-size: 24rpx;

        padding: 0 14rpx;
        border-right: 2rpx solid #e9e9e9;
      }

      // .small_font {
      //   font-size: var(--font-size-small);
      // }

      // .small-medium {
      //   font-size: var(--font-size-medium);
      // }

      // .small-large {
      //   font-size: var(--font-size-large);
      // }

      .outline {
        color: #999;
      }

      .icon {
        width: 10rpx;
        height: 10rpx;
        border-radius: 50%;
        margin-right: 8rpx;
        background-color: #999999;
      }
    }

    .warning {
      background: rgb(250, 237, 237);
      padding: 10rpx 32rpx;

      .warning_title {
        display: flex;
        align-items: center;
        // font-size: 24rpx;
        color: #c92a2a;

        image {
          width: 38rpx;
          height: 38rpx;
          margin-right: 10rpx;
        }
      }

      // .small_font {
      //   font-size: var(--font-size-small);
      // }

      // .small-medium {
      //   font-size: var(--font-size-medium);
      // }

      // .small-large {
      //   font-size: var(--font-size-large);
      // }
    }

    .third {
      margin: 32rpx 30rpx 0;

      .device_working {
        padding: 0 20rpx;
        height: 124rpx;
        font-weight: 500;
        border: 2rpx solid #efefef;
        border-radius: 16rpx;
        position: relative;
        // font-size: 24rpx;
        ;
        margin-right: 20rpx;

        image {
          width: 52rpx;
          height: 52rpx;
          margin-right: 20rpx;
        }

        .info_box {
          &_title {
            font-weight: bold;
            color: #333;
            text-align: center;
          }

          &_radio {
            // width: 110rpx;
            color: #333;
          }
        }

        .activeimg {
          image {
            position: absolute;
            top: 0;
            right: -22rpx;
            width: 38rpx;
            height: 32rpx;
          }
        }

        &.column-layout {
          padding: 15px 0;
          flex-direction: column;
          justify-content: flex-start;
          height: auto;
          min-height: 134rpx;

          .wx_img {
            margin-right: 0;
          }

          .jw_img {
            margin-right: 0;
          }

          // align-items: center;
          .qw_img {
            width: 52rpx;
            height: 52rpx;
            margin-right: 0;
          }
        }
      }

      .isactive {
        border: 2rpx solid #00a57d;
      }

      .gray {
        background: #f5f6f7;
        opacity: 0.5;
      }

      .device_working:last-child {
        margin-right: 0;
      }
    }

    .device_btn {
      height: 88rpx;
      line-height: 88rpx;
      // font-size: 24rpx;
      text-align: center;
      border-radius: 16rpx;
      margin: 32rpx 32rpx 20rpx;
      color: #ffffff;
      background: linear-gradient(90deg, #00a67e, #006d56);
    }

    .device_start_btn {
      color: #ffffff;
      background: linear-gradient(90deg, #00a67e, #006d56);
    }

    .device_working_btn {
      color: #ffffff;
      background: #e5e5e5;
    }

    .device_stop_btn {
      color: #ffffff;
      background: linear-gradient(301deg, #ff9055 3%, #f6e850 75%);
    }
  }

  .device_item:first-child {
    margin-top: 0;
  }

  .device_add {
    height: 88rpx;
    border: 2rpx solid #efefef;
    border-radius: 16rpx;
    margin: 20rpx 32rpx 0;
    background-color: #fff;
    // font-size: 24rpx;

    image {
      width: 24rpx;
      height: 24rpx;
    }
  }

  .space {
    height: 90rpx;
  }

  .blank {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    // font-size: 24rpx;
    color: #999999;
    padding-top: 90rpx;

    image {
      width: 186rpx;
      height: 186rpx;
      margin-bottom: 12rpx;
    }

    .bkank_add {
      width: 302rpx;
      height: 88rpx;
      // font-size: 24rpx;
      color: #ffffff;
      background: linear-gradient(90deg, #00a67e, #006d56);
      border-radius: 44rpx;
      margin-top: 56rpx;

      image {
        width: 24rpx;
        height: 24rpx;
        margin-right: 20rpx;
      }
    }
  }
}

.Mosquito_time {
  height: 400rpx;
  padding: 32rpx;

  .choose_modal_time {
    margin-top: 60rpx;
    width: 210rpx;
    height: 84rpx;
    background: #fff;
    border-radius: 16rpx;
    border: 2rpx solid #efefef;
    line-height: 84rpx;
    color: #333;
    text-align: center;
    position: relative;
  }

  .activeimg {
    image {
      width: 40rpx;
      height: 32rpx;
      position: absolute;
      top: 0;
      right: 0;
    }
  }

  .activeTime {
    width: 210rpx;
    height: 84rpx;
    border: 2rpx solid #00a57d;
    border-radius: 16rpx;
    line-height: 84rpx;
    text-align: center;
    // font-size: 24rpx;
    color: #333;
  }

  .modalBtn_two {
    width: 686rpx;
    margin: 160rpx auto;
    height: 88rpx;
    line-height: 88rpx;
    background: linear-gradient(90deg, #00a67e, #006d56);
    border-radius: 16rpx;
    text-align: center;
    color: #fff;
    // font-size: 24rpx;
  }
}
</style>
